/* m = new Megafeed("http://co:8000/feed.json", "asset")
 * m.load({per_page:2}, function(data){alert(data);});
 * m.getPage(2, function(data){alert(data);});
 * or 
 * m = new Megafeed("http://co:8000/feed.json", "asset",
 *                  function(data){alert(data);})
 * m.load({}); m.getPage(2);
 */
JSON_CALLBACK = 'jsonp'
function Megafeed(base, feed, callback){
    this.callback = callback;
    function process(manager, callback, page){
        return function data(input){
            manager.data = input.response[feed];
            if (page && manager.data.page_data.current_page != page)
                throw 'Returned Page ' + manager.data.page_data.current_page + ' not ' + page + '.'
            if (callback) callback(manager.data);
            else if (manager.callback) manager.callback(manager.data);
            else throw 'No callback defined!';
        }
    }
    if (!base || !feed) throw 'Feed is not defined!';
    else {
        this.base = base;
        this.feed = feed;
    }
    this.load = function(params, callback, page){
        rparams = {};
        this.last_params = params;
        rparams[feed] = $.toJSON(params);
        $.getJSON(base + '?' + JSON_CALLBACK + '=?', rparams,
            process(this, callback, page));
        return this;
    };
    this.getPage = function(page, callback){
        if (!this.last_params) throw 'Must first load paginated data!';
        if (page > 0){
            this.last_params.page = page;
            this.load(this.last_params, callback, page);
            return this;
        } else throw 'Page numbers don\'t bend that way!';
    }
}
